package example.连续部分.公共连续部分.前缀;

// 最长公共前缀 前缀
public class Demo1 {

    public String longestCommonPrefix2(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int length = strs[0].length();
        int count = strs.length;
        for (int i = 0; i < length; i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < count; j++) {
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    return strs[0].substring(0, i);
                }
            }
        }
        return strs[0];
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        //只有一个，返回这一个
        if (strs.length == 1) {
            return strs[0];
        }
        //字符串最小的下标
        int lenMin = 0;
        for (int i = 1; i < strs.length; i++) {
            if (strs[i].length() < strs[lenMin].length()) {
                lenMin = i;
            }
        }
        char[] chars = new char[strs[lenMin].length()];
        commonStr(strs, chars, 0, lenMin);
        return new String(chars).trim();
    }

    //拿strs最小的字符串去比较 与 其他字符串对比
    public static void commonStr(String[] strs, char[] desc, int charAtStart, int lenMin) {
        //超过最小长度，就不需要了
        if (charAtStart >= strs[lenMin].length()) {
            return;
        }
        for (int i = 0; i < strs.length; i++) {
            if (strs[i].charAt(charAtStart) != strs[lenMin].charAt(charAtStart)) {
                return;
            }
        }
        //所有的都匹配，放进去
        desc[charAtStart] = strs[lenMin].charAt(charAtStart);
        commonStr(strs, desc, charAtStart + 1, lenMin);
    }

    public static void main(String[] args) {
//        String[] strs = {"flower", "flow", "flight"};
        String[] strs = {"aaa", "aa", "aaa"};

        String s = longestCommonPrefix(strs);

        System.out.println(s);
    }
}
